<!DOCTYPE HTML>
<html lang="zh-Hans" class="sidebar-visible no-js light">
    <head>
        <!-- Book generated using mdBook -->
        <meta charset="UTF-8">
        <title>进击的Rust多线程——混合自旋锁 - Rust 优秀博文</title>


        <!-- Custom HTML head -->
        
        <meta content="text/html; charset=utf-8" http-equiv="Content-Type">
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="theme-color" content="#ffffff" />

        <link rel="icon" href="../../favicon.svg">
        <link rel="shortcut icon" href="../../favicon.png">
        <link rel="stylesheet" href="../../css/variables.css">
        <link rel="stylesheet" href="../../css/general.css">
        <link rel="stylesheet" href="../../css/chrome.css">
        <link rel="stylesheet" href="../../css/print.css" media="print">

        <!-- Fonts -->
        <link rel="stylesheet" href="../../FontAwesome/css/font-awesome.css">
        <link rel="stylesheet" href="../../fonts/fonts.css">

        <!-- Highlight.js Stylesheets -->
        <link rel="stylesheet" href="../../highlight.css">
        <link rel="stylesheet" href="../../tomorrow-night.css">
        <link rel="stylesheet" href="../../ayu-highlight.css">

        <!-- Custom theme stylesheets -->

    </head>
    <body>
        <!-- Provide site root to javascript -->
        <script type="text/javascript">
            var path_to_root = "../../";
            var default_theme = window.matchMedia("(prefers-color-scheme: dark)").matches ? "navy" : "light";
        </script>

        <!-- Work around some values being stored in localStorage wrapped in quotes -->
        <script type="text/javascript">
            try {
                var theme = localStorage.getItem('mdbook-theme');
                var sidebar = localStorage.getItem('mdbook-sidebar');

                if (theme.startsWith('"') && theme.endsWith('"')) {
                    localStorage.setItem('mdbook-theme', theme.slice(1, theme.length - 1));
                }

                if (sidebar.startsWith('"') && sidebar.endsWith('"')) {
                    localStorage.setItem('mdbook-sidebar', sidebar.slice(1, sidebar.length - 1));
                }
            } catch (e) { }
        </script>

        <!-- Set the theme before any content is loaded, prevents flash -->
        <script type="text/javascript">
            var theme;
            try { theme = localStorage.getItem('mdbook-theme'); } catch(e) { }
            if (theme === null || theme === undefined) { theme = default_theme; }
            var html = document.querySelector('html');
            html.classList.remove('no-js')
            html.classList.remove('light')
            html.classList.add(theme);
            html.classList.add('js');
        </script>

        <!-- Hide / unhide sidebar before it is displayed -->
        <script type="text/javascript">
            var html = document.querySelector('html');
            var sidebar = 'hidden';
            if (document.body.clientWidth >= 1080) {
                try { sidebar = localStorage.getItem('mdbook-sidebar'); } catch(e) { }
                sidebar = sidebar || 'visible';
            }
            html.classList.remove('sidebar-visible');
            html.classList.add("sidebar-" + sidebar);
        </script>

        <nav id="sidebar" class="sidebar" aria-label="Table of contents">
            <div class="sidebar-scrollbox">
                <ol class="chapter"><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">1.</strong> 类型系统</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow.html"><strong aria-hidden="true">1.1.</strong> Rust Concept Clarification Deref vs AsRef vs Borrow vs Cow</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust_Concept_Clarification_Deref_vs_AsRef_vs_Borrow_vs_Cow/Deref_AsRef_Borrow_Cow释义.html"><strong aria-hidden="true">1.2.</strong> Deref AsRef Borrow Cow 释义</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然/Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然.html"><strong aria-hidden="true">1.3.</strong> Rust的Borrow和AsRef：让你的代码用起来像呼吸一样自然</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust的Cow类型有什么用？详解Cow及其用途/Rust的Cow类型有什么用？详解Cow及其用途.html"><strong aria-hidden="true">1.4.</strong> Rust的Cow类型有什么用？详解Cow及其用途</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/判别Fn、FnMut、FnOnce的标准/判别Fn、FnMut、FnOnce的标准.html"><strong aria-hidden="true">1.5.</strong> 判别Fn、FnMut、FnOnce的标准</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/一行代码告诉你内部可变性的真相(UnsafeCell)/一行代码告诉你内部可变性的真相(UnsafeCell).html"><strong aria-hidden="true">1.6.</strong> 一行代码告诉你内部可变性的真相(UnsafeCell)</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Tour_of_Rust's_Standard_Library_Traits/Tour_of_Rust's_Standard_Library_Traits.html"><strong aria-hidden="true">1.7.</strong> Tour of Rust's Standard Library Traits</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/逆变、协变与子类型，以及Rust/逆变、协变与子类型，以及Rust.html"><strong aria-hidden="true">1.8.</strong> 逆变、协变与子类型，以及Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust自引用结构、Pin与Unpin/Rust自引用结构、Pin与Unpin.html"><strong aria-hidden="true">1.9.</strong> Rust自引用结构、Pin与Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/为什么Rust需要Pin,Unpin/为什么Rust需要Pin,Unpin.html"><strong aria-hidden="true">1.10.</strong> 译：为什么 Rust 需要 Pin, Unpin ？</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/定海神针Pin和Unpin/定海神针Pin和Unpin.html"><strong aria-hidden="true">1.11.</strong> 译：定海神针 Pin 和 Unpin</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/sizedness-in-rust/sizedness-in-rust.html"><strong aria-hidden="true">1.12.</strong> Sizedness in Rust</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/Rust生命周期集大成者PhantomData〈T〉/Rust生命周期集大成者PhantomData〈T〉.html"><strong aria-hidden="true">1.13.</strong> Rust生命周期集大成者 PhantomData&lt;T&gt;</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操_Part_0.html"><strong aria-hidden="true">1.14.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操 Part 0</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：GAT实现引用类型关联_Part_1.html"><strong aria-hidden="true">1.15.</strong> 数据库表达式执行的黑魔法：GAT实现引用类型关联 Part 1</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用HRTB写bound_Part_2.html"><strong aria-hidden="true">1.16.</strong> 数据库表达式执行的黑魔法：用HRTB写bound Part 2</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码_Part_3_&_4.html"><strong aria-hidden="true">1.17.</strong> 数据库表达式执行的黑魔法：用Rust做类型体操之用宏展开重复代码 Part 3 & 4</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化_Part_5_&_6.html"><strong aria-hidden="true">1.18.</strong> 数据库表达式执行的黑魔法：与Rust编译器斗智斗勇之表达式向量化 Part 5 & 6</a></li><li class="chapter-item expanded "><a href="../../01_类型系统/数据库表达式执行的黑魔法：用Rust做类型体操/数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型_Part_7.html"><strong aria-hidden="true">1.19.</strong> 数据库表达式执行的黑魔法：在Rust中用宏关联逻辑类型和实际类型 Part 7</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">2.</strong> 生命周期</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../02_生命周期/Rust中的生命周期——从StrSplit实例说开去/Rust中的生命周期——从StrSplit实例说开去.html"><strong aria-hidden="true">2.1.</strong> Rust中的生命周期——从StrSplit实例说开去</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/与ChatGPT深度对话来学Rust生命周期/与ChatGPT深度对话来学Rust生命周期.html"><strong aria-hidden="true">2.2.</strong> 与ChatGPT深度对话来学Rust生命周期</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（1）/进击的Rust生命周期——early_bound与late_bound（1）.html"><strong aria-hidden="true">2.3.</strong> 进击的Rust生命周期——early_bound与late_bound（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——early_bound与late_bound（2）/进击的Rust生命周期——early_bound与late_bound（2）.html"><strong aria-hidden="true">2.4.</strong> 进击的Rust生命周期——early_bound与late_bound（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（1）/进击的Rust生命周期——一力降十会的MIR（1）.html"><strong aria-hidden="true">2.5.</strong> 进击的Rust生命周期——一力降十会的MIR（1）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/进击的Rust生命周期——一力降十会的MIR（2）/进击的Rust生命周期——一力降十会的MIR（2）.html"><strong aria-hidden="true">2.6.</strong> 进击的Rust生命周期——一力降十会的MIR（2）</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Common_Rust_Lifetime_Misconceptions/Common_Rust_Lifetime_Misconceptions.html"><strong aria-hidden="true">2.7.</strong> Common Rust Lifetime Misconceptions</a></li><li class="chapter-item expanded "><a href="../../02_生命周期/Rust生命周期常见误区/Rust生命周期常见误区.html"><strong aria-hidden="true">2.8.</strong> 译：Rust生命周期常见误区</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">3.</strong> 无畏并发</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../05_无畏并发/简单写个Rust无锁队列/简单写个Rust无锁队列.html"><strong aria-hidden="true">3.1.</strong> 简单写个Rust无锁队列</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——混合自旋锁/进击的Rust多线程——混合自旋锁.html" class="active"><strong aria-hidden="true">3.2.</strong> 进击的Rust多线程——混合自旋锁</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/An_unsafe_tour_of_Rust's_Send_and_Sync/An_unsafe_tour_of_Rust's_Send_and_Sync.html"><strong aria-hidden="true">3.3.</strong> An unsafe tour of Rust's Send and Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——Send与Sync/进击的Rust多线程——Send与Sync.html"><strong aria-hidden="true">3.4.</strong> 进击的Rust多线程——Send与Sync</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/进击的Rust多线程——离经叛道的PhantomData/进击的Rust多线程——离经叛道的PhantomData.html"><strong aria-hidden="true">3.5.</strong> 进击的Rust多线程——离经叛道的PhantomData</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust_Async_Pin概念解析/Rust_Async_Pin概念解析.html"><strong aria-hidden="true">3.6.</strong> Rust Async: Pin概念解析</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust和C++的并发库对比/Rust和C++的并发库对比.html"><strong aria-hidden="true">3.7.</strong> 译：Rust 和 C++ 的并发库对比</a></li><li class="chapter-item expanded "><a href="../../05_无畏并发/Rust原子类型和内存排序/Rust原子类型和内存排序.html"><strong aria-hidden="true">3.8.</strong> Rust原子类型和内存排序</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">4.</strong> 网络编程</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../06_网络编程/从编解码层面理解WebSocket_手写一个WebSocket/从编解码层面理解WebSocket_手写一个WebSocket.html"><strong aria-hidden="true">4.1.</strong> 从编解码层面理解WebSocket 手写一 个WebSocket</a></li><li class="chapter-item expanded "><a href="../../06_网络编程/透过Rust探索系统的本原：网络篇/透过Rust探索系统的本原：网络篇.html"><strong aria-hidden="true">4.2.</strong> 透过Rust探索系统的本原：网络篇</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">5.</strong> 轮子系列</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../07_轮子系列/700行Rust写一个内存分配器/700行Rust写一个内存分配器.html"><strong aria-hidden="true">5.1.</strong> 700行Rust写一个内存分配器</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust：网络库的实现思路/Rust：网络库的实现思路.html"><strong aria-hidden="true">5.2.</strong> Rust：网络库的实现思路</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/Rust异步运行时基础部件/Rust异步运行时基础部件.html"><strong aria-hidden="true">5.3.</strong> Rust异步运行时基础部件</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（1）.html"><strong aria-hidden="true">5.4.</strong> 使用Rust+epoll编写异步IO框架（1）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（2）.html"><strong aria-hidden="true">5.5.</strong> 使用Rust+epoll编写异步IO框架（2）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/使用Rust+epoll编写异步IO框架/使用Rust+epoll编写异步IO框架（3）.html"><strong aria-hidden="true">5.6.</strong> 使用Rust+epoll编写异步IO框架（3）</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day1.html"><strong aria-hidden="true">5.7.</strong> 用rust从零开发一套web框架：day1</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day2.html"><strong aria-hidden="true">5.8.</strong> 用rust从零开发一套web框架：day2</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day3.html"><strong aria-hidden="true">5.9.</strong> 用rust从零开发一套web框架：day3</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day4.html"><strong aria-hidden="true">5.10.</strong> 用rust从零开发一套web框架：day4</a></li><li class="chapter-item expanded "><a href="../../07_轮子系列/用rust从零开发一套web框架/用rust从零开发一套web框架：day5.html"><strong aria-hidden="true">5.11.</strong> 用rust从零开发一套web框架：day5</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">6.</strong> 奇技淫巧</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Copy-On-Write是不是优化？/Copy-On-Write是不是优化？.html"><strong aria-hidden="true">6.1.</strong> 译：Copy-On-Write是不是优化？</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/揭秘神奇的Rust_Axum风格的函数实现/揭秘神奇的Rust_Axum风格的函数实现.html"><strong aria-hidden="true">6.2.</strong> 译：揭秘神奇的 Rust Axum 风格的函数实现</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/“变长参数”函数与回调/“变长参数”函数与回调.html"><strong aria-hidden="true">6.3.</strong> “变长参数”函数与回调</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Rust字符串格式化的幕后：format_args!()/Rust字符串格式化的幕后：format_args!().html"><strong aria-hidden="true">6.4.</strong> 译：Rust字符串格式化的幕后：format_args!()</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/给Rust带来一点C++特产/给Rust带来一点C++特产.html"><strong aria-hidden="true">6.5.</strong> 给Rust带来一点C++特产</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/一步步实现_Rust_Bevy_ECS_的_System_简化版本/一步步实现_Rust_Bevy_ECS_的_System_简化版本.html"><strong aria-hidden="true">6.6.</strong> 一步步实现 Rust Bevy ECS 的 System 简化版本</a></li><li class="chapter-item expanded "><a href="../../08_奇技淫巧/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples/Exploring_Design_Patterns_in_Rust_with_Algorithmic_Trading_Examples.html"><strong aria-hidden="true">6.7.</strong> Exploring Design Patterns in Rust with Algorithmic Trading Examples</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">7.</strong> 源码分析</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：bytes源码分析/Rust并发：bytes源码分析.html"><strong aria-hidden="true">7.1.</strong> Rust并发：bytes源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库Arc源码分析/Rust并发：标准库Arc源码分析.html"><strong aria-hidden="true">7.2.</strong> Rust并发：标准库Arc源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust并发：标准库sync_Once源码分析/Rust并发：标准库sync_Once源码分析.html"><strong aria-hidden="true">7.3.</strong> Rust并发：标准库sync::Once源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：引用计数Rc/Rust源码阅读：引用计数Rc.html"><strong aria-hidden="true">7.4.</strong> Rust源码阅读：引用计数Rc</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust源码阅读：Cell、RefCell与内部可变性/Rust源码阅读：Cell、RefCell与内部可变性.html"><strong aria-hidden="true">7.5.</strong> Rust源码阅读： Cell、RefCell与内部可变性</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/关于_Rust_的_UnsafeCell、Cell_与_RefCell/关于_Rust_的_UnsafeCell、Cell_与_RefCell.html"><strong aria-hidden="true">7.6.</strong> 关于 Rust 的 UnsafeCell、Cell 与 RefCell</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Async_async-stream源码分析/Rust_Async_async-stream源码分析.html"><strong aria-hidden="true">7.7.</strong> Rust Async: async-stream源码分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/走进Tokio的异步世界/走进Tokio的异步世界.html"><strong aria-hidden="true">7.8.</strong> 走进 Tokio 的异步世界</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/tokio.rs_runtime的实现/tokio.rs_runtime的实现.html"><strong aria-hidden="true">7.9.</strong> tokio.rs runtime 的实现</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/Tokio_internals.html"><strong aria-hidden="true">7.10.</strong> Tokio internals</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_internals/译文：Tokio內部机制.html"><strong aria-hidden="true">7.11.</strong> 译：Tokio 内部机制</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Rust_Axum_HTTP_框架的架构分析/Rust_Axum_HTTP_框架的架构分析.html"><strong aria-hidden="true">7.12.</strong> Rust Axum HTTP 框架的架构分析</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/安利一个Rust_Game_Engine：Bevy--ECS部分/安利一个Rust_Game_Engine：Bevy--ECS部分.html"><strong aria-hidden="true">7.13.</strong> 安利一个Rust Game Engine：Bevy--ECS部分</a></li><li class="chapter-item expanded "><a href="../../09_源码分析/Tokio_解析之任务调度/Tokio_解析之任务调度.html"><strong aria-hidden="true">7.14.</strong> Tokio 解析之任务调度</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">8.</strong> 生态观察</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../11_生态观察/Rust_web_frameworks_have_subpar_error_reporting/Rust_web_frameworks_have_subpar_error_reporting.html"><strong aria-hidden="true">8.1.</strong> Rust web frameworks have subpar error reporting</a></li><li class="chapter-item expanded "><a href="../../11_生态观察/SeaORM：要做Rust版本的ActiveRecord/SeaORM：要做Rust版本的ActiveRecord.html"><strong aria-hidden="true">8.2.</strong> SeaORM：要做Rust版本的ActiveRecord</a></li></ol></li><li class="chapter-item expanded "><a href="../../empty.html"><strong aria-hidden="true">9.</strong> 死灵终极</a></li><li><ol class="section"><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_总述.html"><strong aria-hidden="true">9.1.</strong> 译：Learn Rust the Dangerous Way 总述</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_0.html"><strong aria-hidden="true">9.2.</strong> 译：Learn Rust the Dangerous Way 0</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_1.html"><strong aria-hidden="true">9.3.</strong> 译：Learn Rust the Dangerous Way 1</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_2.html"><strong aria-hidden="true">9.4.</strong> 译：Learn Rust the Dangerous Way 2</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_3.html"><strong aria-hidden="true">9.5.</strong> 译：Learn Rust the Dangerous Way 3</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_4.html"><strong aria-hidden="true">9.6.</strong> 译：Learn Rust the Dangerous Way 4</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Learn_Rust_the_Dangerous_Way_系列文章翻译/Learn_Rust_the_Dangerous_Way_系列文章翻译_5.html"><strong aria-hidden="true">9.7.</strong> 译：Learn Rust the Dangerous Way 5</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（一）.html"><strong aria-hidden="true">9.8.</strong> Unsafe Rust 随堂小测（一）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（二）.html"><strong aria-hidden="true">9.9.</strong> Unsafe Rust 随堂小测（二）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测（三）.html"><strong aria-hidden="true">9.10.</strong> Unsafe Rust 随堂小测（三）</a></li><li class="chapter-item expanded "><a href="../../12_死灵终极/Unsafe_Rust_随堂小测/Unsafe_Rust_随堂小测参考答案.html"><strong aria-hidden="true">9.11.</strong> Unsafe Rust 随堂小测参考答案</a></li></ol></li></ol>
            </div>
            <div id="sidebar-resize-handle" class="sidebar-resize-handle"></div>
        </nav>

        <div id="page-wrapper" class="page-wrapper">

            <div class="page">
                                <div id="menu-bar-hover-placeholder"></div>
                <div id="menu-bar" class="menu-bar sticky bordered">
                    <div class="left-buttons">
                        <button id="sidebar-toggle" class="icon-button" type="button" title="Toggle Table of Contents" aria-label="Toggle Table of Contents" aria-controls="sidebar">
                            <i class="fa fa-bars"></i>
                        </button>
                        <button id="theme-toggle" class="icon-button" type="button" title="Change theme" aria-label="Change theme" aria-haspopup="true" aria-expanded="false" aria-controls="theme-list">
                            <i class="fa fa-paint-brush"></i>
                        </button>
                        <ul id="theme-list" class="theme-popup" aria-label="Themes" role="menu">
                            <li role="none"><button role="menuitem" class="theme" id="light">Light (default)</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="rust">Rust</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="coal">Coal</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="navy">Navy</button></li>
                            <li role="none"><button role="menuitem" class="theme" id="ayu">Ayu</button></li>
                        </ul>
                        <button id="search-toggle" class="icon-button" type="button" title="Search. (Shortkey: s)" aria-label="Toggle Searchbar" aria-expanded="false" aria-keyshortcuts="S" aria-controls="searchbar">
                            <i class="fa fa-search"></i>
                        </button>
                    </div>

                    <h1 class="menu-title">Rust 优秀博文</h1>

                    <div class="right-buttons">
                        <a href="../../print.html" title="Print this book" aria-label="Print this book">
                            <i id="print-button" class="fa fa-print"></i>
                        </a>

                    </div>
                </div>

                <div id="search-wrapper" class="hidden">
                    <form id="searchbar-outer" class="searchbar-outer">
                        <input type="search" id="searchbar" name="searchbar" placeholder="Search this book ..." aria-controls="searchresults-outer" aria-describedby="searchresults-header">
                    </form>
                    <div id="searchresults-outer" class="searchresults-outer hidden">
                        <div id="searchresults-header" class="searchresults-header"></div>
                        <ul id="searchresults">
                        </ul>
                    </div>
                </div>

                <!-- Apply ARIA attributes after the sidebar and the sidebar toggle button are added to the DOM -->
                <script type="text/javascript">
                    document.getElementById('sidebar-toggle').setAttribute('aria-expanded', sidebar === 'visible');
                    document.getElementById('sidebar').setAttribute('aria-hidden', sidebar !== 'visible');
                    Array.from(document.querySelectorAll('#sidebar a')).forEach(function(link) {
                        link.setAttribute('tabIndex', sidebar === 'visible' ? 0 : -1);
                    });
                </script>

                <div id="content" class="content">
                    <main>
                        <h1 id="进击的rust多线程混合自旋锁"><a class="header" href="#进击的rust多线程混合自旋锁">进击的Rust多线程——混合自旋锁</a></h1>
<p>作者：<a href="https://www.zhihu.com/people/you-ni-de-meng">有你的梦</a></p>
<p>原载：<a href="https://zhuanlan.zhihu.com/p/413659832">https://zhuanlan.zhihu.com/p/413659832</a></p>
<p>本文涉及的内容为：互斥锁与自旋锁概念、二进制指数退避算法的概念、crossbeam_util包backoff组件源码精读、crossbeam_channel包Spinlock混合自旋锁组件源码精读。</p>
<h2 id="互斥锁与自旋锁"><a class="header" href="#互斥锁与自旋锁">互斥锁与自旋锁</a></h2>
<p>互斥锁是指<strong>标记某个数据，使其在任一时刻只能有一个线程访问该数据</strong>。互斥可以理解为互相排斥，我拿着你就不能拿。而自旋锁属于互斥锁的一种，也就是说上面关于互斥锁的定义对自旋锁适用，同时自旋锁还加了自己的规矩。**若一个线程尝试获取锁中数据的访问权失败则继续尝试，直到获得数据为止。**死循环就死循环，还自旋，整的挺高级。</p>
<p>所以大家也可以明白，自旋锁是一种简单粗暴的互斥锁的实现方式。一般的互斥锁在尝试获得锁失败的时候会挂起线程，或者使线程暂时休眠，这样的逻辑可以节约服务器资源，在大多数场景中很实用。想来也没问题，一般获得锁失败了，证明当前数据正在被其他线程使用，那么一时半会儿自然是不会交出所有权的。类似我们去图书馆借书，发现想借的书已经借出去了，那我们大概率会换一本书借，或者放弃借书的打算，下次来碰碰运气。而自旋锁则是一个爱钻牛角尖的杠精。“什么？书没了是吧，那我就坐在这等别人来还书，不吃不睡。”</p>
<p>所以自旋锁也有优点，毕竟它可以更迅速的获得锁资源，而付出的代价就是CPU一段时间的空转，对性能是一种浪费。但同时，自旋锁更加简单直接的抢夺逻辑在锁使用时间快的场景下反而是一种高效的做法，因为它不需要像其他的互斥锁一样需要处理频繁的上下文切换，不停地在各个线程间睡眠唤醒。</p>
<h2 id="二进制指数退避算法"><a class="header" href="#二进制指数退避算法">二进制指数退避算法</a></h2>
<p>看起来很高级的概念，拆分一下其实就是利用二进制指数实现的退避算法。先把前面的忽略掉，什么是退避算法呢？退避其实就是适当的后退，优雅的回避。**退避算法就是指当计算机指令出现阻塞时，当前线程暂时挂起的算法。**退一步海阔天空。举个例子，假设线程通过自旋锁获取数据时，如果出现了阻塞，就会不停请求直到获取数据为止。如果锁使用的时间很长，就会产生大量的无效请求占用CPU资源。而这时就需要回避算法了，它其实是一种调度算法，讲究的是过犹不及。既要限制大量无效的请求，又要保持足够的敏捷响应。</p>
<p>二进制指数退避算法是退避算法的一种实现方式，其实就是指请求次数越多，请求的时间间隔就越长。时间间隔和请求次数之间存在二进制指数关系。比如第一次请求失败了，第二次请求间隔一秒，第三次请求间隔两秒，第四次请求间隔四秒，第四次请求间隔八秒。。。同时配合一个最大尝试次数，如果到达上限则自动判定超时。一般会有一个随机数的设置，使过程更平滑，我这里简化了一下逻辑方便理解。想必大家也能猜到，此算法在网络通信中经常出境。</p>
<p>为了可以更直观的看出二进制退避算法的优化效果，我专门做了个图。如图2-1所示，X轴为单位时间，y轴是访问次数总计，设定1单位时间内的无限制访问次数为100。蓝色是未使用退避算法的数据模型，总数和时间无限制，呈线性增长。而橙色是使用了二进制级数退避算法的数据模型。</p>
<p><img src="assets/0100.webp" alt="" /></p>
<h2 id="crossbeam_util包backoff源码精读"><a class="header" href="#crossbeam_util包backoff源码精读">crossbeam_util包backoff源码精读</a></h2>
<p>这个组件实现了上面提到的二进制级数退避算法。</p>
<p><a href="https://doc.servo.org/crossbeam_utils/backoff/struct.Backoff.html#">https://doc.servo.org/crossbeam_utils/backoff/struct.Backoff.html#</a></p>
<p>话不多说直接看源码。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>const SPIN_LIMIT: u32 = 6;
const YIELD_LIMIT: u32 = 10;
<span class="boring">}
</span></code></pre></pre>
<p>开头定义了两个u32常量，具体是做什么的后面会提到。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub struct Backoff {
    step: Cell&lt;u32&gt;,
}
<span class="boring">}
</span></code></pre></pre>
<p><code>Backoff</code>就是实现这个算法的主体。里面包含的<code>step</code>，是表示当前尝试的次数，所以使用Cell包装，保证它内部可变性。</p>
<p>接下来是<code>Backoff</code>自带的方法:</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn new() -&gt; Self {
        Backoff { step: Cell::new(0) }
    }
<span class="boring">}
</span></code></pre></pre>
<p><code>Backoff</code>的初始化，<code>step</code>设置为0。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn reset(&amp;self) {
        self.step.set(0);
    }
<span class="boring">}
</span></code></pre></pre>
<p>重置<code>Backoff</code>，将<code>step</code>设置为0。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn spin(&amp;self) {
        for _ in 0..1 &lt;&lt; self.step.get().min(SPIN_LIMIT) {
            // 一旦我们将所需的最低 Rust 版本提高到 1.49+，请改用 [`core::hint::spin_loop`]。
            #[allow(deprecated)]
            atomic::spin_loop_hint();
        }

        if self.step.get() &lt;= SPIN_LIMIT {
            self.step.set(self.step.get() + 1);
        }
    }
<span class="boring">}
</span></code></pre></pre>
<p>这是一个重要的方法。首先是一个<code>for</code>循环，<code>0..1 &lt;&lt; self.step.get().min(SPIN_LIMIT)</code>通过位运算实现了二进制级数循环。简单的例子说明如下：</p>
<p><strong>代码2-1：</strong></p>
<pre><pre class="playground"><code class="language-rust">fn main() {
    println!(&quot;级数1&quot;);
    for i in 0..1 &lt;&lt; 1 {
        print!(&quot;{}，&quot;, i);
    }
    println!(&quot;&quot;);
    println!(&quot;级数2&quot;);
    for i in 0..1 &lt;&lt; 2 {
        print!(&quot;{}，&quot;, i);
    }
    println!(&quot;&quot;);
    println!(&quot;级数3&quot;);
    for i in 0..1 &lt;&lt; 3 {
        print!(&quot;{}，&quot;, i);
    }
}
级数1
0，1，
级数2
0，1，2，3，
级数3
0，1，2，3，4，5，6，7，
</code></pre></pre>
<p>在此处二进制级数通过<code>min</code>函数计算得到，可以看出<code>SPIN_LIMIT</code>的意义是循环的上限。</p>
<p>循环体的内容也有的一说。<code>atomic::spin_loop_hint();</code>上面的注释中提到的内容来看这是为了兼容低版本而使用的函数，而代替它的新版本的函数是<code>core::hint::spin_loop</code>。具体的文档在这里。</p>
<p><a href="https://doc.rust-lang.org/core/sync/atomic/fn.spin_loop_hint.html#">https://doc.rust-lang.org/core/sync/atomic/fn.spin_loop_hint.html#</a></p>
<p>文档中有句描述很生动。</p>
<blockquote>
<p>Emits a machine instruction to signal the processor that it is running in a busy-wait spin-loop (“spin lock”).
Upon receiving the spin-loop signal the processor can optimize its behavior by, for example, saving power or switching hyper-threads.
发出一条机器指令，向处理器发出信号，表明它正在一个忙碌等待的自旋循环(自旋锁)中运行。一旦接收到自旋循环信号，处理器就可以通过节省电源或切换超线程来优化其行为。</p>
</blockquote>
<p>所以说，这个for循环就是用来做自旋锁阻塞优化的。它在循环中提示处理器，我当前处于自旋锁空转中，然后计算机会对其进行相应的优化。</p>
<p>循环结束之后，<code>spin_loop_hint</code>停止。第8-10行，如果<code>step</code>小于等于<code>SPIN_LIMIT</code>，则加一。</p>
<p>所以这个<code>spin</code>方法，每次调用时都会按当前的<code>step</code>进行一段时间的循环，在循环中通知处理器对当前阻塞行为进行优化，随后给<code>step</code>累加1。这样不停调用此方法，<code>step</code>会变大，而for循环次数则会按2的<code>step</code>次方增加。直到<code>step</code>达到<code>SPIN_LIMIT</code>之后，for循环次数会固定为2的6次方。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub fn snooze(&amp;self) {
        if self.step.get() &lt;= SPIN_LIMIT {
            for _ in 0..1 &lt;&lt; self.step.get() {
                // 一旦我们将所需的最低 Rust 版本提高到 1.49+，请改用 [`core::hint::spin_loop`]。
                #[allow(deprecated)]
                atomic::spin_loop_hint();
            }
        } else {
            #[cfg(not(feature = &quot;std&quot;))]
            for _ in 0..1 &lt;&lt; self.step.get() {
                // 一旦我们将所需的最低 Rust 版本提高到 1.49+，请改用 [`core::hint::spin_loop`]。
                #[allow(deprecated)]
                atomic::spin_loop_hint();
            }

            #[cfg(feature = &quot;std&quot;)]
            ::std::thread::yield_now();
        }

        if self.step.get() &lt;= YIELD_LIMIT {
            self.step.set(self.step.get() + 1);
        }
    }
<span class="boring">}
</span></code></pre></pre>
<p>接下来是<code>snooze</code>方法。该方法首先判断<code>step</code>是否小于等于<code>SPIN_LIMIT</code>，如果是则和<code>spin</code>逻辑相同，区别在于累加时的判断条件变成了<code>step</code>是否小于等于<code>YIELD_LIMIT</code>。所以六次调用之后<code>step</code>一定会超过<code>SPIN_LIMIT</code>，如果<code>step</code>大于<code>SPIN_LIMIT</code>，除了会循环并调用<code>spin_loop_hint</code>之外，还会执行<code>::std::thread::yield_now();</code></p>
<p><a href="https://doc.rust-lang.org/std/thread/fn.yield_now.html#">https://doc.rust-lang.org/std/thread/fn.yield_now.html#</a></p>
<p>下面是对文档中重要描述的引用。</p>
<blockquote>
<p>This calls the underlying OS scheduler s yield primitive, signaling that the calling thread is willing to give up its remaining timeslice so that the OS may schedule other threads on the CPU.
它调用底层OS调度器的yield原语，表明调用线程愿意放弃剩余的时间片，以便OS可以调度CPU上的其他线程。</p>
</blockquote>
<p>它的作用是告诉计算机，我应该会长时间阻塞在这，你先忙别的吧。</p>
<p><code>snooze</code>翻译为中文是打盹。所以它和<code>spin</code>的区别是，<code>spin</code>是伸个懒腰，<code>snooze</code>是小睡一会儿。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>#[inline]
    pub fn is_completed(&amp;self) -&gt; bool {
        self.step.get() &gt; YIELD_LIMIT
    }
<span class="boring">}
</span></code></pre></pre>
<p>判断当前<code>step</code>是否大于<code>YIELD_LIMIT</code>。即当前计数器进度是否已经满了。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl fmt::Debug for Backoff {
    fn fmt(&amp;self, f: &amp;mut fmt::Formatter&lt;'_&gt;) -&gt; fmt::Result {
        f.debug_struct(&quot;Backoff&quot;)
            .field(&quot;step&quot;, &amp;self.step)
            .field(&quot;is_completed&quot;, &amp;self.is_completed())
            .finish()
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>之后为<code>Backoff</code>实现了<code>Debug</code>，一会儿我们可以试试。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl Default for Backoff {
    fn default() -&gt; Backoff {
        Backoff::new()
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>再然后又实现了<code>Default</code>，给<code>Backoff</code>添加了默认值的支持。</p>
<p>代码就是这样，我们接下来试试它的威力。</p>
<p><strong>代码2-2：</strong></p>
<pre><pre class="playground"><code class="language-rust">use crossbeam_utils::Backoff;
use std::sync::Arc;
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::SeqCst;
use std::thread;
use std::time::Duration;

fn spin_wait(ready: &amp;AtomicBool) {
    let backoff = Backoff::new();
    let mut attempt_count = 0;
    while !ready.load(SeqCst) {
        backoff.snooze();
        attempt_count = attempt_count + 1;
        println!(&quot;{}, {:?}&quot;, attempt_count, backoff);
    }
}

fn main() {
    let ready = Arc::new(AtomicBool::new(false));
    let ready2 = ready.clone();

    thread::spawn(move || {
        thread::sleep(Duration::from_millis(100));
        ready2.store(true, SeqCst);
    });

    assert_eq!(ready.load(SeqCst), false);
    spin_wait(&amp;ready);
    assert_eq!(ready.load(SeqCst), true);
}
</code></pre></pre>
<p>执行结果：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>...
374, Backoff { step: Cell { value: 11 }, is_completed: true }
375, Backoff { step: Cell { value: 11 }, is_completed: true }
376, Backoff { step: Cell { value: 11 }, is_completed: true }
377, Backoff { step: Cell { value: 11 }, is_completed: true }
378, Backoff { step: Cell { value: 11 }, is_completed: true }
379, Backoff { step: Cell { value: 11 }, is_completed: true }
380, Backoff { step: Cell { value: 11 }, is_completed: true }
381, Backoff { step: Cell { value: 11 }, is_completed: true }
<span class="boring">}
</span></code></pre></pre>
<p>每调用一次while模拟一次自旋阻塞，总共执行了381次。</p>
<p>那么接下来我们试一下把第12行代码<code>backoff.snooze();</code>注释掉，再跑一次。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>...
510, Backoff { step: Cell { value: 0 }, is_completed: false }
511, Backoff { step: Cell { value: 0 }, is_completed: false }
512, Backoff { step: Cell { value: 0 }, is_completed: false }
513, Backoff { step: Cell { value: 0 }, is_completed: false }
514, Backoff { step: Cell { value: 0 }, is_completed: false }
515, Backoff { step: Cell { value: 0 }, is_completed: false }
<span class="boring">}
</span></code></pre></pre>
<p>所以使用Backoff大概相当于减少了40%的请求次数，我觉得还挺ok的。各位可以自己试一下，把阻塞时间设置的长一些会更加明显。</p>
<h2 id="crossbeam_channel包spinlock混合自旋锁组件源码精读"><a class="header" href="#crossbeam_channel包spinlock混合自旋锁组件源码精读">crossbeam_channel包Spinlock混合自旋锁组件源码精读</a></h2>
<p>终于到了本教程的重点了，其实本来我就是读到这个自旋锁，然后一步一步向上追寻真相，才有了上面的内容。如果你把前面提到的内容全部理解了，那下面就会很好懂。</p>
<p>首先解释下什么是混合自旋锁，其实就是<strong>先自旋，如果自旋短时间内不能拿到锁，就挂起线程等待</strong>。它结合了上面讲到的自旋锁和一般互斥锁的优点。</p>
<p><a href="https://doc.servo.org/crossbeam_channel/utils/struct.Spinlock.html#">https://doc.servo.org/crossbeam_channel/utils/struct.Spinlock.html#</a></p>
<p>下面进入代码：</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub(crate) struct Spinlock&lt;T&gt; {
    flag: AtomicBool,
    value: UnsafeCell&lt;T&gt;,
}
<span class="boring">}
</span></code></pre></pre>
<p>这是自旋锁的结构，<code>flag</code>代表锁的状态，<code>value</code>代表锁的数据（使用<code>UnsafeCell</code>，代表锁为持有者提供了修改内容的权限）。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;T&gt; Spinlock&lt;T&gt; {
    /// Returns a new spinlock initialized with `value`.
    pub(crate) fn new(value: T) -&gt; Spinlock&lt;T&gt; {
        Spinlock {
            flag: AtomicBool::new(false),
            value: UnsafeCell::new(value),
        }
    }

    /// Locks the spinlock.
    pub(crate) fn lock(&amp;self) -&gt; SpinlockGuard&lt;'_, T&gt; {
        let backoff = Backoff::new();
        while self.flag.swap(true, Ordering::Acquire) {
            backoff.snooze();
        }
        SpinlockGuard { parent: self }
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>然后为它实现了两个方法。</p>
<p><code>new</code>，创建一个锁。</p>
<p><code>lock</code>，获取锁。首先是创建一个<code>Backoff</code>，然后循环尝试修改<code>flag</code>为<code>true</code>。<code>swap</code>函数是修改<code>flag</code>的值，并返回它原先的值。所以就是说，如果原先是<code>true</code>，则继续循环，直到原先的值为<code>false</code>，证明当前线程抢到锁了，则跳出循环。循环内容就是上面讲的<code>backoff.snooze();</code>，它表明，如果尝试抢锁超过6次，那对不起，你先睡会儿。如果抢锁成功，则返回<code>SpinlockGuard</code>。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>pub(crate) struct SpinlockGuard&lt;'a, T&gt; {
    parent: &amp;'a Spinlock&lt;T&gt;,
}
<span class="boring">}
</span></code></pre></pre>
<p><code>SpinlockGuard</code>中包含了当前锁的引用。注意它是一个不可变引用，也就意味着你拿到锁之后，锁引用是不能改的。拿到哪个锁就是哪个。但是我需要操作<code>Spinlock</code>中的<code>value</code>，这也就是为什么使用<code>UnsafeCell</code>包装value的原因。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;T&gt; Deref for SpinlockGuard&lt;'_, T&gt; {
    type Target = T;

    fn deref(&amp;self) -&gt; &amp;T {
        unsafe { &amp;*self.parent.value.get() }
    }
}

impl&lt;T&gt; DerefMut for SpinlockGuard&lt;'_, T&gt; {
    fn deref_mut(&amp;mut self) -&gt; &amp;mut T {
        unsafe { &amp;mut *self.parent.value.get() }
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>后面为<code>SpinlockGuard</code>实现了<code>Deref</code>和<code>DerefMut</code>。对它的引用和可变引用将会直接返回<code>Spinlock</code>中的<code>value</code>内容。这样就对外隐藏了<code>SpinlockGuard</code>，使整个锁尽可能的简洁。</p>
<pre><pre class="playground"><code class="language-rust"><span class="boring">#![allow(unused)]
</span><span class="boring">fn main() {
</span>impl&lt;T&gt; Drop for SpinlockGuard&lt;'_, T&gt; {
    fn drop(&amp;mut self) {
        self.parent.flag.store(false, Ordering::Release);
    }
}
<span class="boring">}
</span></code></pre></pre>
<p>接下来为<code>SpinlockGuard</code>实现了<code>Drop</code>，它是整个锁逻辑的精妙所在。当<code>SpinlockGuard</code>被销毁时，将它的<code>Spinlock</code>锁状态改为<code>false</code>，相当于利用了Rust的所有权机制自动还锁，这样用户就不需要手动去还锁了，优雅。</p>
<p>编辑于 2021-09-24 20:35</p>

                    </main>

                    <nav class="nav-wrapper" aria-label="Page navigation">
                        <!-- Mobile navigation buttons -->
                            <a rel="prev" href="../../05_无畏并发/简单写个Rust无锁队列/简单写个Rust无锁队列.html" class="mobile-nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                                <i class="fa fa-angle-left"></i>
                            </a>

                            <a rel="next" href="../../05_无畏并发/An_unsafe_tour_of_Rust&#x27;s_Send_and_Sync/An_unsafe_tour_of_Rust&#x27;s_Send_and_Sync.html" class="mobile-nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                                <i class="fa fa-angle-right"></i>
                            </a>

                        <div style="clear: both"></div>
                    </nav>
                </div>
            </div>

            <nav class="nav-wide-wrapper" aria-label="Page navigation">
                    <a rel="prev" href="../../05_无畏并发/简单写个Rust无锁队列/简单写个Rust无锁队列.html" class="nav-chapters previous" title="Previous chapter" aria-label="Previous chapter" aria-keyshortcuts="Left">
                        <i class="fa fa-angle-left"></i>
                    </a>

                    <a rel="next" href="../../05_无畏并发/An_unsafe_tour_of_Rust&#x27;s_Send_and_Sync/An_unsafe_tour_of_Rust&#x27;s_Send_and_Sync.html" class="nav-chapters next" title="Next chapter" aria-label="Next chapter" aria-keyshortcuts="Right">
                        <i class="fa fa-angle-right"></i>
                    </a>
            </nav>

        </div>




        <script type="text/javascript">
            window.playground_copyable = true;
        </script>


        <script src="../../elasticlunr.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../mark.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../searcher.js" type="text/javascript" charset="utf-8"></script>

        <script src="../../clipboard.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../highlight.js" type="text/javascript" charset="utf-8"></script>
        <script src="../../book.js" type="text/javascript" charset="utf-8"></script>

        <!-- Custom JS scripts -->


    </body>
</html>
